/**
 * @Author:卿雨欣
 * @Date:2020/7/7
 * @Description:这是推荐产品列表组件
 */
import React,{Component} from "react";
import {ListView, Tag, SearchBar, Toast, Menu, ActivityIndicator, NavBar, Icon, WhiteSpace} from "antd-mobile";
import axios from "axios";
import {getCookieRisk} from "../../Login/Component_Login/GetCookie";
var data_list=[]
var scroll_list=false;
const NUM_ROWS = 20;
let pageIndex = 0;

function genData(pIndex = 0) {
    const dataBlob = {};
    for (let i = 0; i < NUM_ROWS; i++) {
        const ii = (pIndex * NUM_ROWS) + i;
        dataBlob[`${ii}`] = `row - ${ii}`;
    }
    return dataBlob;
}
// 将获取的数据中属性为数字的转换为文字
function numberName(newList){
    for(let i=0;i<newList.length;i++) {
        var ratio = newList[i].totalIncomeRadio;
        newList[i].totalIncomeRadio = Number(ratio*100).toFixed(2)+"%";
        switch (newList[i].comBaseCate) {
            case 1:
                newList[i].comBaseCate = "股票型";
                break;
            case 2:
                newList[i].comBaseCate = "基金型";
                break;
            case 3:
                newList[i].comBaseCate = "混合型";
                break;
        }
        switch (newList[i].comBaseRiskLevel) {
            case 1:
                newList[i].comBaseRiskLevel ="谨慎型";
                break;
            case 2:
                newList[i].comBaseRiskLevel ="稳健型";
                break;
            case 3:
                newList[i].comBaseRiskLevel ="平衡型";
                break;
            case 4:
                newList[i].comBaseRiskLevel ="进取型";
                break;
            default:
                newList[i].comBaseRiskLevel ="激进型";
                break;
        }
        switch (newList[i].isUsed) {
            case 0:
                newList[i].isUsed ="已下架";
                break;
            case 1:
                newList[i].isUsed="预售";
                break;
            case 2:
                newList[i].isUsed ="正在运行";
                break;
        }
    }
    return newList;
};
export default class ListViewRecommend extends Component {
    constructor(...args) {
        super(...args);
        //ListView的dataSource初始化
        const dataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        this.state = {
            initData: '',
            show: false,
            //listView
            dataSource,
            isLoading: true,
            data_list:[],
            value:"" ,//搜索栏文字
            pageSize:0,
        };
        this.handleCancel.bind(this);
        this.genData.bind(this)
    }
    // 提交搜索 values:搜索框中的字符串
    searchSubmit = (values) =>{
        //初始化产品列表的dataSource
        const newDataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        var newDataList = []; //符合搜索条件的新数组
        for(let i=0;i<this.state.data_list.length;i++){
            //查询组合代码
            if(this.state.data_list[i].comBaseCode.indexOf(values) != -1){
                newDataList.push(this.state.data_list[i])
            }
            //查询组合名称
            if(this.state.data_list[i].comBaseName.indexOf(values) != -1){
                newDataList.push(this.state.data_list[i])
            }
        }
        //未查询到符合条件的产品，进行提示
        if(newDataList.length == 0){
            Toast.info("未查找到符合条件的产品")
        }else{
            //查询到，更新产品列表listView的dataSource以及列表的item数组data_list，列表展示的数据条数pageSize
            this.setState({
                data_list:newDataList,
                pageSize:newDataList.length,
                dataSource:newDataSource,
            })
            //重新加载产品列表数据dataSource
            this.componentDidMount();
        }
    }
    //初始化产品列表的行列
    genData(pIndex = 0) {
        var NUM_ROWS = this.state.pageSize;
        const dataBlob = {};
        for (let i = 0; i < NUM_ROWS; i++) {
            const ii = (pIndex * NUM_ROWS) + i;
            dataBlob[`${ii}`] = `row - ${ii}`;
        }
        return dataBlob;
    }
    //搜索栏 取消操作
    handleCancel =(value)=>{
        //初始化产品列表的dataSource
        const newDataSource = new ListView.DataSource({
            rowHasChanged: (row1, row2) => row1 !== row2,
        });
        //取消查询清空搜索框的值，恢复产品列表，更新产品列表listView的dataSource以及列表的item数组data_list，列表展示的数据条数pageSize
        this.setState({
            data_list:data_list,
            value:"",
            pageSize:data_list.length,
            dataSource:newDataSource,
        })
        //重新加载产品列表数据dataSource
        this.componentDidMount();
    }
    //搜索栏 值改变的回调函数
    onChangeSearch= (value) => {
        this.setState({ value });
    };
    //获取页面数据
    componentWillMount() {
        axios({
            method:"GET",
            url:"http://39.101.141.248:9527/combinations/getCombinationsList",
            params:{riskLevel:getCookieRisk()}
        }).then(res=>{
            if(res.data.code == 200){
                data_list=numberName(res.data.combinationList) //将对象内的数字属性转化为文字
                this.setState({
                    data_list:data_list,
                    pageSize:data_list.length,
                })
            }
        }).catch(error=>{
            console.log(error);
        });
    }
    //请求初始化数据
    componentDidMount() {
        setTimeout(() => {
            this.rData = this.genData();
            this.setState({
                dataSource: this.state.dataSource.cloneWithRows(this.rData),
                isLoading: false,
            });
        }, 600);
    }
    // 分页请求
    onEndReached = (event) => {
        if (this.state.isLoading) {
            return;
        }
    }

    render() {
        const { initData, show } = this.state;
        const menuEl = ( //筛选菜单
            <Menu
                className="foo-menu"
                data={initData}
                /*   value={['1','2']}*/
                onChange={this.onChange}
                height={document.documentElement.clientHeight * 0.6}
            />
        );
        const loadingEl = ( //面板
            <div style={{ width: '100%', height: document.documentElement.clientHeight * 0.6, display: 'flex', justifyContent: 'center' }}>
                <ActivityIndicator size="large" />
            </div>
        );

        //ListView间隔
        const separator = (sectionID, rowID) => (
            <div
                key={`${sectionID}-${rowID}`}
                style={{
                    backgroundColor: '#F5F5F9',
                    height: 8,
                    borderTop: '1px solid #ECECED',
                    borderBottom: '1px solid #ECECED',
                }}
            />
        );
        let index = this.state.data_list.length - 1;
        //列表的item
        const row = (rowData, sectionID, rowID) => {
            if (index < 0) {
                index = this.state.data_list.length - 1;
            }
            const obj = this.state.data_list[index--];
            return (
                <div key={rowID} style={{ padding: '0 15px' }}>
                    <div
                        style={{
                            lineHeight: '50px',
                            color: '#888',
                            fontSize: 18,
                            borderBottom: '1px solid #F6F6F6',
                        }}
                    >
                        {obj.comBaseName}
                        <Tag style={{color:"#f8a83f",float:"right",marginTop:13}}>{obj.comBaseCate}</Tag>
                    </div>
                    <div style={{ display: '-webkit-box,flex', padding: '10px 0' }}>
                        {/* <img style={{ height: '64px', marginRight: '15px' }} src={obj.img} alt="" />*/}
                        <div style={{ lineHeight: 1 }}>
                            <div className="productList" >
                                <ul className="productList-ul" >
                                    <li className="font3">
                                        {obj.comBaseRiskLevel}
                                        <p className="gray-text">风险等级</p>
                                    </li>
                                    <li className="font1">
                                        {obj.totalIncomeRadio}
                                        <p className="gray-text">成立以来收益率</p>
                                    </li>
                                    <li className="font2">
                                        {obj.isUsed}
                                        <p className="gray-text">组合状态</p>
                                    </li>
                                </ul>
                            </div>
                        </div>
                    </div>
                </div>
            );
        };

        return (
            <div >
                <div className={show ? 'menu-active' : ''}>
                    <div style={{position:"fixed",zIndex:500,top:0,left:0,width:"100%"}}>
                        <NavBar
                            mode="light"
                            icon={<Icon type="left" style={{color:" #f8a83f"}} />}
                            onLeftClick={() => window.history.back(-1)}
                            rightContent={
                                <img src={require("../../../access/images/filterProductList.png")}
                                     className="am-icon am-icon-md"
                                     onClick={this.handleClick}/>
                            }
                        >
                            <SearchBar value={this.state.value}
                                       style={{width:"230%",zIndex:99,marginLeft:-100,marginRight:-100}}
                                       onCancel={value => this.handleCancel(value)}
                                       onSubmit={value =>this.searchSubmit(value)}
                                       onChange={this.onChangeSearch}
                                       placeholder="组合代码/名称/经理/公司等关键词"  />
                        </NavBar>
                    </div>
                    {show ? initData ? menuEl : loadingEl : null}
                    {show ? <div className="menu-mask" onClick={this.onMaskClick} /> : null}
                </div>
                <WhiteSpace size="lg"/>
                <WhiteSpace size="lg"/>
                <div style={{height:25}}></div>
                <div className={scroll_list ? 'list-scroll' : ''} >
                    <ListView
                        ref={el => this.lv = el}
                        dataSource={this.state.dataSource}
                        renderFooter={() => (<div style={{ padding: 0, textAlign: 'center' }}>
                            {this.state.isLoading ? '加载中' : '已全部加载'}
                        </div>)}
                        renderRow={row}
                        renderSeparator={separator}
                        className="am-list"
                        pageSize={this.state.pageSize}
                        scrollEventThrottle={5}
                        useBodyScroll
                        onScroll={() => { console.log('scroll'); }}
                        scrollRenderAheadDistance={500}
                        onEndReached={this.onEndReached}
                        onEndReachedThreshold={10}
                    />
                </div>
            </div>
        );
    }
}